<template>
  <div class="yxactive">
    <div class="yxactive_main">
      <div class="card_top">
        <el-card :body-style="{ padding: '10' }" style="text-align: left;">
          <div class="taber">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="进行中" name="1"> </el-tab-pane>
              <el-tab-pane label="过期活动" name="2"> </el-tab-pane>
              <el-tab-pane label="未开始" name="3"> </el-tab-pane>
            </el-tabs>
            <div>
              <div style="width:100%">
                <el-button
                  @click="openDialog(1)"
                  style="width: 100%;margin-bottom:8px;height:35px;line-height: 10px;"
                  ><div>新增活动</div></el-button
                >
              </div>
              <div>
                <el-table
                  v-loading="loading"
                  :data="tableData"
                  style="width: 100%"
                  :cell-style="rowClass"
                  :header-cell-style="headClass"
                  ref="singleTable"
                  @current-change="handleCurrentChange"
                  highlight-current-row
                >
                  <!-- fixed -->
                  <el-table-column prop="activity_id" label="活动id">
                    <template slot-scope="scope">
                      <div>{{ scope.row.activity_id }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="activity_name" label="活动名称">
                    <template slot-scope="scope">
                      <div style="text-align:center">
                        {{ scope.row.activity_name }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="activity_start_time"
                    label="活动开始时间"
                  >
                    <template slot-scope="scope">
                      <div>
                        {{
                          scope.row.activity_start_time
                            | formatTime("yyyy-MM-dd hh:mm:ss")
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="activity_end_time"
                    label="活动结束时间"
                  >
                    <template slot-scope="scope">
                      <div>
                        {{
                          scope.row.activity_end_time
                            | formatTime("yyyy-MM-dd hh:mm:ss")
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="create_at" label="创建时间">
                    <template slot-scope="scope">
                      <span>{{ scope.row.create_at }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="update_at" label="修改时间">
                    <template slot-scope="scope">
                      <span>{{ scope.row.update_at }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="action" label="操作">
                    <template slot-scope="scope">
                      <el-button
                        style="margin-left: 10px;"
                        @click.native.prevent="openDialog(scope.row)"
                        type="text"
                        size="small"
                        >编辑
                      </el-button>
                      <el-popconfirm
                        confirmButtonText="确定"
                        cancelButtonText="取消"
                        confirmButtonType="text"
                        icon="el-icon-info"
                        iconColor="red"
                        @onConfirm="close(scope.row)"
                        title="确定删除吗？"
                      >
                        <el-button slot="reference" type="text" size="small"
                          >删除
                        </el-button>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
                <div style="width:100%;text-align:right">
                  <!-- 分页器 -->
                  <!-- @size-change="handleSizeChange" -->
                  <!-- background -->
                  <el-pagination
                    @current-change="handleCurrentChange2"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    :pager-count="11"
                    layout="total, prev, pager, next, jumper"
                    :total="count"
                  >
                    <!-- :page-sizes="[100, 200, 300, 400]" -->
                  </el-pagination>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div>
        <el-dialog
          width="550px"
          :title="isadd ? '新增活动' : '修改活动'"
          :visible.sync="dialogFormVisible"
          center
        >
          <el-form
            :model="form"
            status-icon
            :rules="rules"
            :before-close="handleClose"
            ref="ruleForm"
          >
            <el-form-item
              label="活动名称"
              prop="activity_name"
              :label-width="formLabelWidth"
            >
              <el-input
                style="width:220px"
                v-model.trim="form.activity_name"
                autocomplete="off"
                placeholder="请输入活动名称"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="开始时间"
              prop="activity_start_time"
              :label-width="formLabelWidth"
            >
              <el-date-picker
                v-model="form.activity_start_time"
                type="datetime"
                placeholder="选择开始时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="结束时间"
              prop="activity_end_time"
              :label-width="formLabelWidth"
            >
              <el-date-picker
                v-model="form.activity_end_time"
                type="datetime"
                placeholder="选择结束时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
              >
                <!-- value-format="yyyy-MM-dd HH:mm:ss" -->
              </el-date-picker>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
// import { getAdminGoods, doRejectGoods, doPassGoods } from "@/api/local/audit";
import {
  getActivityList,
  addActivity,
  delActivity,
  updateActivity
} from "@/api/userinfo/userinfo";
export default {
  filters: {
    formatTime: function(datetime, fmt) {
      var date = new Date(datetime);
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      var o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds()
      };
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          var str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
          );
        }
      }
      return fmt;
    }
  },
  name: "yxactive",
  data() {
    var activity_name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入活动名称！"));
      } else {
        callback();
      }
    };
    var activity_start_time = (rule, value, callback) => {
      console.log(value);
      if (value.toString() == "") {
        callback(new Error("请填写开始时间"));
      } else {
        callback();
      }
    };
    var activity_end_time = (rule, value, callback) => {
      if (value.toString() == "") {
        callback(new Error("请填写结束时间"));
      }
      if (this.form.activity_start_time >= this.form.activity_end_time) {
        callback(new Error("结束时间不能小于或等于开始时间!"));
      } else {
        callback();
      }
    };
    return {
      pagesize: 30,
      currentPage: 1,
      count: 0,
      isadd: true,
      dialogFormVisible: false,
      form: {
        activity_name: "",
        activity_start_time: "",
        activity_end_time: ""
      },
      rules: {
        activity_name: [{ validator: activity_name, trigger: "blur" }],
        activity_start_time: [
          { validator: activity_start_time, trigger: "blur" }
        ],
        activity_end_time: [{ validator: activity_end_time, trigger: "blur" }]
      },
      formLabelWidth: "170px",
      loading: false,
      activeName: "1",
      tableData: [
        // {
        //   activity_id: 3, //活动id
        //   activity_name: "测试活动", //活动名称
        //   activity_start_time: 1589250760, //活动开始时间
        //   activity_end_time: 1589337160, // 活动结束时间
        //   create_at: "2020-05-12 10:35:47", // 创建时间
        //   update_at: "2020-05-12 10:35:47" //修改时间
        // }
      ]
    };
  },

  computed: {},
  created() {
    this.getActivityList(1, 15);
  },
  mounted() {},
  methods: {
    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getActivityList(this.currentPage, 15, parseInt(this.activeName));
    },
    //删除活动
    delActivity(activity_id) {
      delActivity({
        activity_id: activity_id
      })
        .then(res => {
          if (res.code == 200) {
            console.log("返回", res);
            this.$message.success("删除成功!");
            this.getActivityList(1, 15);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //新增活动
    addActivity() {
      addActivity({
        ...this.form
      })
        .then(res => {
          if (res.code == 200) {
            console.log("返回", res);
            this.$message.success("新增成功!");
            this.getActivityList(1, 15);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //修改活动
    updateActivity() {
      updateActivity({
        ...this.form
      })
        .then(res => {
          if (res.code == 200) {
            console.log("返回", res);
            this.$message.success("修改成功!");
            this.getActivityList(1, 15);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    submitForm(formName) {
      console.log("表单内容", this.form);
      this.form.activity_start_time = parseInt(
        this.form.activity_start_time.toString().substring(0, 10)
      );
      this.form.activity_end_time = parseInt(
        this.form.activity_end_time.toString().substring(0, 10)
      );
      this.dialogFormVisible = false;
      this.$refs[formName].validate(valid => {
        //   console.log("valid", valid);
        if (valid) {
          if (this.form.activity_id) {
            this.updateActivity();
            this.form = this.$options.data().form;
          } else {
            this.addActivity();
            this.form = this.$options.data().form;
          }
        } else {
          this.$message.error("请检查表单!");
        }
      });
    },
    handleClose() {
      this.form = {};
      this.resetForm("ruleForm");
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
    },
    openDialog(row) {
      this.dialogFormVisible = true;
      this.isadd = true;
      this.form = this.$options.data().form;
      if (row !== 1) {
        console.log(row);
        this.form = row;
        this.isadd = false;
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      console.log(this.form);
    },
    // 获取列表
    getActivityList(page, pagesize, type) {
      this.loading = true;
      getActivityList({
        page: page,
        pagesize: pagesize,
        type: type
      })
        .then(res => {
          this.loading = false;
          console.log("活动列表", res);
          this.tableData = res.data.data;
          this.count = res.data.count;
          for (var i = 0; i < this.tableData.length; i++) {
            this.tableData[i].activity_start_time = parseInt(
              this.tableData[i].activity_start_time.toString() + "000"
            );
            this.tableData[i].activity_end_time = parseInt(
              this.tableData[i].activity_end_time.toString() + "000"
            );
          }
          console.log(this.tableData);
        })
        .catch(err => {
          console.log(err);
        });
    },

    close(row) {
      console.log("确认删除", row);
      this.delActivity(row.activity_id);
    },
    // 表头背景色
    headClass() {
      return "text-align: center;background:#eef1f6;";
    },
    // 表格样式设置
    rowClass() {
      return "text-align: center;";
    },
    // 表格选中行高亮
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    // 导航栏切换
    handleClick(tab, event) {
      console.log(tab.name, event);
      this.activeName = tab.name;
      this.getActivityList(1, 15, parseInt(this.activeName));
    }
  }
};
</script>

<style lang="less" scoped>
.yxactive {
  // width: 970px;
  box-sizing: border-box;
  // .yxactive_main::v-deep {
  //   // width: 970px;
  // }
}
</style>
